package com.gm.blog.service.impl;

import com.gm.blog.mapper.BlogMapper;
import com.gm.blog.mapper.TypeMapper;
import com.gm.blog.pojo.Blog;
import com.gm.blog.pojo.Type;
import com.gm.blog.service.BlogService;
import com.gm.blog.utils.Page;
import com.gm.blog.vo.BlogVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class BlogServiceImpl implements BlogService {

    @Autowired
    private BlogMapper blogMapper;

    @Autowired
    private TypeMapper typeMapper;
    /**
     * 添加博客
     * @param blog
     */
    @Override
    public void save(Blog blog) {
        blogMapper.save(blog);
    }

    /**
     * 修改博客信息
     * @param blog
     */
    @Override
    public void update(Blog blog) {
        blogMapper.update(blog);
    }

    /**
     * 根据ID查询博客数据
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BlogVo readById(Integer id) {
        Blog blog = blogMapper.getById(id);
        blog.setBlogRead(blog.getBlogRead()+1);
        blogMapper.update(blog);
        //将blog转为blogVo
        BlogVo blogVo=new BlogVo();
        BeanUtils.copyProperties(blog,blogVo);
        //查询分类
        Type type = typeMapper.getTypeById(blog.getBlogType());
        blogVo.setTypeName(type.getTypeName());
        return blogVo;
    }

    /**
     * 更具ID删除数据
     * @param id
     */
    @Override
    public void delete(Integer id) {
        blogMapper.delete(id);
    }

    /**
     * 更具分页查询数据
     * @param page
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Page<BlogVo> getByPage(Page<BlogVo> page) {
        //获取当前分页
        List<BlogVo> pageList = blogMapper.getByPage(page);
        page.setList(pageList);
        //获取分页数量
        int countByPage = blogMapper.getCountByPage(page);
        page.setTotalCount(countByPage);
        return page;
    }

}
